//
//  HomeFocusController.m
//  OnionHome
//
//  Created by fengjie on 2019/9/16.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "HomeFocusController.h"
#import "HomeFocusCell.h"
#import "HomeAddFocusController.h"
#import "HomeSwitchFocusOnUsersController.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "HomeFocusModel.h"

@interface HomeFocusController ()<UITableViewDelegate,UITableViewDataSource>
/**listView*/
@property (nonatomic,strong)UITableView*listView;
/**headerView*/
@property (nonatomic,strong)UIView*headerView;
@property (nonatomic , strong)NSMutableArray *dataArray;
@end

@implementation HomeFocusController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.listView];
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    DLogFunc;
    [self setNotificationCenter];
}
-(void)setNotificationCenter{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadLocaData) name:K_ReleaseTextAndImage object:nil];
}
-(void)reloadLocaData{
    self.dataArray = nil;
    [self.listView reloadData];
}
//查询全部
- (void)query {
//    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];
    
    // 获取文件路径
    NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"user" ofType:@"db"];
    
    FMDatabase *dataBase = [FMDatabase databaseWithPath:dbPath];
    if (![dataBase open]) {
        DLog(@"打开数据库失败");
        return ;
    }
    FMResultSet *resultSet = [dataBase executeQuery:@"select * from user"];
    while ([resultSet next]) {
        NSString *name = [resultSet stringForColumn:@"name"];
        int commentCount = [resultSet intForColumn:@"commentCount"];
        int praiseCount = [resultSet intForColumn:@"praiseCount"];
        
        DLog(@"Name:%@,commentCount:%d,praiseCount:%d",name,commentCount,praiseCount);
        
        HomeFocusModel *homeFocusModel = [[HomeFocusModel alloc] init];
        homeFocusModel.name = name;
        homeFocusModel.commentCount = commentCount;
        homeFocusModel.praiseCount = praiseCount;
        [self.dataArray addObject:homeFocusModel];
        
    }
    
    [dataBase close];
    
    [self.listView reloadData];
    
    DLog(@"打印一下所有的数组 %@",self.dataArray);
}



- (void)insertData{
    //获取Document文件夹下的数据库文件，没有则创建
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];
    DLog(@"dbPath = %@",dbPath);
    //获取数据库并打开
    //  FMDatabase *dataBase = [FMDatabase databaseWithPath:dbPath];
    
    //多线程安全FMDatabaseQueue可以替代dataBase
    FMDatabaseQueue *dataBasequeue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
    
    
    [dataBasequeue inDatabase:^(FMDatabase *db) {
        
        
        if (![db open]) {
            DLog(@"打开数据库失败");
            return ;
        }
        //创建表（FMDB中只有update和query操作，除了查询其他都是update操作）
        [db executeUpdate:@"create table if not exists user(name text,commentCount integer,praiseCount integer) "];
        
        //常用方法有以下3种：
        //    - (BOOL)executeUpdate:(NSString*)sql, ...
        //    - (BOOL)executeUpdateWithFormat:(NSString*)format, ...
        //    - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments
        
        
        //插入数据
        BOOL insert = [db executeUpdate:@"insert into user values(?,?,?)",@"冯杰",@"233",@"899"];
        if (insert) {
            DLog(@"插入成功");
        }
        
        [db close];
        
        
    }];
    
    
}


#pragma mark --UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 8;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return UIView.new;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return UIView.new;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeFocusCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HomeFocusCell class]) forIndexPath:indexPath];
    HomeFocusTwoImageCell * twoCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HomeFocusTwoImageCell class])];
    HomeFocusMorenImageCell * moreCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HomeFocusMorenImageCell class])];

    if (self.dataArray.count) {
          HomeFocusModel *model = self.dataArray[indexPath.row];
        if (model.imageArray.count == 2) {
            twoCell.homeFocusModel = model;
            return twoCell;
        }
        
        if (model.imageArray.count >= 3 && model.imageArray.count <=9) {
            moreCell.homeFocusModel = model;
            return moreCell;
        }
        
        cell.homeFocusModel = model;
        
    }
    kWeakSelf(weakSelf);
    [cell.bottomView.newsBtn addActionHandler:^{
        [weakSelf.navigationController pushViewController:[ImageAndTextDetailController new] animated:YES];
    }];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.navigationController pushViewController:[ImageAndTextDetailController new] animated:YES];
}
-(UITableView*)listView{
    if(!_listView){
        _listView=[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _listView.delegate = self;
        _listView.dataSource = self;
        _listView.tableFooterView = UIView.new;
        _listView.tableHeaderView = self.headerView;
        _listView.rowHeight = UITableViewAutomaticDimension;
        _listView.estimatedRowHeight = 44.0f;
        [_listView registerClass:[HomeFocusCell class] forCellReuseIdentifier:NSStringFromClass([HomeFocusCell class])];
        [_listView registerClass:[HomeFocusTwoImageCell class] forCellReuseIdentifier:NSStringFromClass([HomeFocusTwoImageCell class])];
        [_listView registerClass:[HomeFocusMorenImageCell class] forCellReuseIdentifier:NSStringFromClass([HomeFocusMorenImageCell class])];
        _listView.backgroundColor = UIColorFromRGB(0xF5F7F5);
        _listView.separatorColor = SeparatorColor;
    }
    return _listView;
}
-(UIView*)headerView{
    if(!_headerView){
        _headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 104)];
        _headerView.backgroundColor = KWhiteColor;
        _headerView.userInteractionEnabled = YES;
        
        NSArray * array = @[@"用户名",@"我是大鲨鱼",@"我我我我...",@"添加关注"];
        CGFloat left = 16;
        CGFloat spacing = 18;
        CGFloat width = 56;
        for (NSInteger i = 0 ; i<array.count; i++) {
            
            UIView * bgView = UIView.new;
            bgView.backgroundColor = KWhiteColor;
            ViewBorderRadius(bgView, width/2, 1, UIColorFromRGB(0x009966));
            bgView.userInteractionEnabled = YES;
            
            UIImageView * imageView = UIImageView.new;
//            imageView.image = IMAGE_NAMED(@"userIconDefut");
            imageView.image = [Utilis getRandomUserImage];
            imageView.layer.cornerRadius = (width - 4)/2;
            imageView.layer.masksToBounds = YES;
//            imageView.layer.borderWidth = 1;
//            imageView.layer.borderColor = UIColorFromRGB(0x009966).CGColor;
            
            UILabel * label = UILabel.new;
            label.text = array[i];
            label.textColor = UIColorFromRGB(0x273323);
            label.font = SYSTEMFONT(12);
            label.textAlignment = NSTextAlignmentCenter;
            
            
            [_headerView addSubview:bgView];
            [_headerView addSubview:label];
            [bgView addSubview:imageView];
            
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.mas_equalTo(0);
                make.width.height.mas_equalTo(width-4);
            }];
            
            imageView.userInteractionEnabled = YES;
            label.userInteractionEnabled = YES;
            imageView.tag = i;
            label.tag = i;
            
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHeaderItemAction:)]];
            [label addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHeaderItemAction:)]];

            
            [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(width);
                make.left.mas_equalTo(left + i * width + i * spacing);
                make.top.mas_equalTo(16);
            }];
            
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(bgView);
                make.top.mas_equalTo(bgView.mas_bottom).offset(10);
            }];
            
            if ([array[i] isEqualToString:@"添加关注"]) {
                imageView.image = [UIImage createImageWithColor:KWhiteColor];
                imageView.layer.borderColor = KWhiteColor.CGColor;
                UIImageView * addImage = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_add_fouce")];
                
                [imageView addSubview:addImage];
                ViewBorderRadius(bgView, width/2, 1, UIColorFromRGB(0xF2F5F0));
                [addImage mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.center.mas_equalTo(0);
                }];
                                          
            }

        }
    }
    return _headerView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
        
        NSMutableArray * oneArray = [PlistTool  getPlistType:ReleseImageAndText];
        if (oneArray.count>0) {
            [oneArray enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                HomeFocusModel *model = [HomeFocusModel new];
                [model setValuesForKeysWithDictionary:obj];
                [_dataArray addObject:model];
            }];
        }
        
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"HomeFocus" ofType:@"plist"];
           //当数据结构为数组时
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
        [array enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            HomeFocusModel *model = [HomeFocusModel new];
            
            [model setValuesForKeysWithDictionary:obj];
            [_dataArray addObject:model];
            
        }];
        

    }
    return _dataArray;
}

-(void)tapHeaderItemAction:(UITapGestureRecognizer *)tap{
    switch (tap.view.tag) {
        case 3:
            [self pushAddFocusAction];
            break;

        default:
            [self showSwithController];
            break;
    }
}
-(void)pushAddFocusAction{
    [self.navigationController pushViewController:[HomeAddFocusController new] animated:YES];
}
-(void)showSwithController{
    PresentationObject * obj = [PresentationObject sharedPresentationObject];
    obj.subViewFrame = CGRectMake(0, 44, KScreenWidth, KScreenHeight-44);
    obj.isShowTopView = YES;
    [obj showPresentingViewController:self PresentedViewController:[HomeSwitchFocusOnUsersController new]];
}
@end

